<?php
/**
 * @Notes QQ登录
 * @author: ysongyang <ysongyang@qq.com>
 * @link
 * @copyright: copyright 2016 ysongyang all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */
namespace app\index\controller;

use app\api\controller\QQConnect;
use app\api\controller\WeiboConnect;
use think\Controller;
use think\Session;
use think\Cookie;
use think\Config;

header("Content-type:text/html;charset=utf-8");

class Oauth extends Controller
{

    /*
    * Type类型，初始化
    * QQConnet  WeiboConnect
    */
    public function index()
    {
        $type = request()->param('type');
        switch ($type) {
            /* QQ互联登录 */
            case 'qq':
                $app_id = config('QQ_AUTH.APP_ID');
                $scope = config('QQ_AUTH.SCOPE');
                $callback = config('QQ_AUTH.CALLBACK');
                $sns = new QQConnect();
                $sns->login($app_id, $callback, $scope);
                break;
            /* 新浪微博登录 */
            case 'sina':
                $app_id = config('SINA_AUTH.APP_ID');
                $scope = config('SINA_AUTH.SCOPE');
                $callback = config('SINA_AUTH.CALLBACK');
                $sns = new WeiboConnect();
                $sns->login($app_id, $callback, $scope);
                break;
            /* 默认无登录 */
            default:
                $this->error("无效的第三方方式", url('index/user/login'));
                break;
        }

    }

    /*
     * 互联登录返回信息
     * 获取code 和 state状态，查询数据库
     * */
    public function callback()
    {
        $type = request()->param('type');
        $user_model = new \app\model\User();
        switch ($type) {
            /* 接受QQ互联登录返回值 */
            case 'qq':
                $code = request()->param('code');
                empty($code) && $this->error("code is empty!", url('index/user/login'));
                $app_id = config('QQ_AUTH.APP_ID');
                $app_key = config('QQ_AUTH.APP_KEY');
                $callback = config('QQ_AUTH.CALLBACK');
                $qq = new QQConnect();
                /*callback返回openid和access_token*/
                $backInfo = $qq->callback($app_id, $app_key, $callback);
                $user = $user_model->search(['openid' => $backInfo['openid']]);
                //如果找到该用户
                if (!empty($user)) {
                    $userinfo = array(
                        'id' => $user['id'],
                        'username' => $user['username'],
                        'headimgurl' => $user['headimgurl'],
                        'level' => $user['level'],
                        'gid' =>getGidByLevel($user['level'])
                    );
                    db('user')->where(array('openid' => $backInfo['openid']))->setInc('loginnum');
                    $where = array('openid' => $backInfo['openid']);
                    $data = array('lastdate' => date('Y-m-d H:i:s'), 'lastip' => get_client_ip());
                    $user_model->saveUser($where, $data);
                    //$backUrl=urldecode($_SESSION['referer']);
                    $keeptime = 604800; //默认一周
                    $salt = Config::get('salt');
                    //第二身份标识
                    $identifier = md5($salt . md5($user['openid'] . $salt));
                    //永久登录标识
                    $token = md5(uniqid(rand(), true));
                    //记录时间
                    $timeout = $keeptime;
                    //登录成功将用户信息存储session
                    Session::set('userinfo', $userinfo);
                    //如果用户勾选了"记住我",则保持持久登陆
                    //存入cookie
                    Cookie::set('loginauth', "$identifier:$token", $timeout);
                    $user_model->saveRemember($user['id'], $identifier, $token, $timeout);
                    $this->redirect('index/user/index'); //set#bind
                }
                /*get_user_info 获取用户信息*/
                $userinfo_qq = $qq->get_user_info($app_id, $backInfo['token'], $backInfo['openid']);
                if ($userinfo_qq['ret'] < 0) {
                    $this->error("QQ登录失败！", url('index/user/login'));
                } else {
                    //如果QQ登录授权成功，则把需要的信息记录保存
                    $user_qq = array(
                        'openid' => $backInfo['openid'],
                        'username' => !empty($user['username'])?$user['username']:$userinfo_qq['nickname'],
                        'headimgurl' => !empty($user['headimgurl'])?$user['headimgurl']:$userinfo_qq['figureurl_2'],
                        'gender' => $userinfo_qq['gender'], //性别
                    );
                    session("user_qq", $user_qq);
                    $this->redirect('index/user/qqbind');
                }

                //防止刷新
                empty($backInfo) && $this->error("请重新授权登录", url('index/user/login'));
                break;
            /* 接受新浪微博登录返回值     */
            case 'sina':
                $code = request()->param('code');
                empty($code) && $this->error("无效的第三方方式", url('index/user/login'));
                $app_id = config('SINA_AUTH.APP_ID');
                $app_key = config('SINA_AUTH.APP_KEY');
                $scope = config('SINA_AUTH.SCOPE');
                $callback = config('SINA_AUTH.CALLBACK');
                $weibo = new WeiboConnect();
                /* callback返回openid和access_toke */
                $backInfo = $weibo->callback($app_id, $app_key, $callback);
                $user = $user_model->search(['sina_openid' => $backInfo['openid']]);
                if (!empty($user)) {
                    $userinfo = array(
                        'id' => $user['id'],
                        'username' => $user['username'],
                        'headimgurl' => $user['headimgurl'],
                        'level' => $user['level'],
                        'gid' =>getGidByLevel($user['level'])
                    );
                    db('user')->where(array('sina_openid' => $backInfo['openid']))->setInc('loginnum');
                    $where = array('sina_openid' => $backInfo['openid']);
                    $data = array('lastdate' => date('Y-m-d H:i:s'), 'lastip' => get_client_ip());
                    $user_model->saveUser($where, $data);
                    //$backUrl=urldecode($_SESSION['referer']);
                    $keeptime = 604800; //默认一周
                    $salt = Config::get('salt');
                    //第二分身标识
                    $identifier = md5($salt . md5($user['sina_openid'] . $salt));
                    //永久登录标识
                    $token = md5(uniqid(rand(), true));
                    //记录时间
                    $timeout = $keeptime;
                    //登录成功将用户信息存储session
                    Session::set('userinfo', $userinfo);
                    //如果用户勾选了"记住我",则保持持久登陆
                    //存入cookie
                    Cookie::set('loginauth', "$identifier:$token", $timeout);
                    $user_model->saveRemember($user['id'], $identifier, $token, $timeout);
                    $this->redirect('index/user/index'); //set#bind
                }
                /*get_user_info 获取用户信息*/
                $userinfo_sina = $weibo->get_user_info($backInfo['token'], $backInfo['openid']);
                empty($backInfo) && $this->error("请重新授权登录", url('index/user/login'));
                $gender = 0;
                if ($userinfo_sina['gender'] == 'm') {
                    $gender = 1;
                } elseif ($userinfo_sina['gender'] == 'f') {
                    $gender = 2;
                }
                //如果QQ登录授权成功，则把需要的信息记录保存
                $user_sina = array(
                    'sina_openid' => $backInfo['openid'],
                    'sina_token' => $backInfo['token'],
                    'username' => $userinfo_sina['screen_name'],
                    'nickname' => $userinfo_sina['screen_name'],
                    'headimage' => $userinfo_sina['avatar_hd'],
                    'gender' => $gender //性别
                );
                session("user_sina", $user_sina);
                $this->redirect('index/user/sinabind');
                break;
            /* 默认错误跳转到登录页面  */
            default:
                $this->error("无效的第三方方式", url('index/user/login'));
                break;
        }
    }
}